// Package userdao
// @Author zhongxc
// @Date 2023/12/12 14:18:00
// @Desc
package userdao

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"zhongxc.cc/admin-common/msdb"
	"zhongxc.cc/admin-common/msdb/gorms"
	"zhongxc.cc/admin-user/internal/model"
)

type SysUserDao struct {
	conn *gorms.GormConn
}

func NewSysUserDao(db *msdb.MsDB) *SysUserDao {
	return &SysUserDao{
		conn: gorms.New(db.Conn),
	}
}

func (d *SysUserDao) FindById(ctx context.Context, userId int64) (user *model.SysUser, err error) {
	session := d.conn.Session(ctx)
	err = session.Model(&model.SysUser{}).
		Where("user_id=?", userId).
		Limit(1).
		Take(&user).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		// 其他异常处理
		return nil, err
	}
	return user, nil
}

func (d *SysUserDao) UpdateById(ctx context.Context, userId int64, user map[string]interface{}) error {
	session := d.conn.Session(ctx)
	err := session.Model(&model.SysUser{}).Where("user_id=?", userId).Updates(user).Error
	return err
}

func (d *SysUserDao) Save(ctx context.Context, user *model.SysUser) error {
	session := d.conn.Session(ctx)
	err := session.Save(user).Error
	return err
}

func (d *SysUserDao) FindByName(ctx context.Context, username string) (sysUser *model.SysUser, err error) {
	session := d.conn.Session(ctx)
	err = session.Model(&model.SysUser{}).
		Where("username=?", username).
		Where("status=?", 1).
		Limit(1).
		Take(&sysUser).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return sysUser, err
}
